package com.hdu.seckilldemo.config;

import com.hdu.seckilldemo.pojo.User;
import com.hdu.seckilldemo.service.IUserService;
import com.hdu.seckilldemo.utils.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//自定义用户参数
@Component
public class UserArgumentResolver implements HandlerMethodArgumentResolver {
    @Autowired
    private IUserService userService;
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        Class<?> type = parameter.getParameterType();
        //如果传入的是User类型，那么会执行下列方法
        return type==User.class;
    }
    //如果supportsParameter方法返回true，那么会接着执行resolveArgument方法。
    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);
        String userTicket = CookieUtil.getCookieValue(request, "userTicket");
        //如果没有登陆信息，跳转到登陆页面
        if (StringUtils.isEmpty(userTicket)) {
            return null;
        }
        //如果有，我们从redis中获取用户信息
        return userService.getUserByCookie(userTicket,request,response);
    }
}
